var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
var router = express.Router();
var mongoose = require('mongoose');
var config = require('./config.js');
var dbConfig = require('./db_config.js');
var envConfig = require('./env/config_development.json');
var session = require("express-session");

//DB
if (dbConfig.mongodb.debug) {
    mongoose.set('debug', true);
}
var db = mongoose.connect(dbConfig.mongodb.uri, dbConfig.mongodb.options, function (err) {
    if (err) {
        console.error('Could not connect to MongoDB!');
        console.error(err);
        process.exit(-1);
    }
    else {
        console.log('Connected to MongoDB!');
    }
});



//Cross origin
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With,X-Powered-By,Content-Type");
    if (req.method === 'OPTIONS') {
        res.status(200).end();
    } else {
        next();
    }
});


// view engine setup
app.set('views', path.join(__dirname, '/../views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');


// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser("session"));
app.use(session({
    secret: 'session',//与cookieParser中的一致
    resave: true,
    saveUninitialized:true
   }));
app.use(express.static("public"));

//登录过滤器
app.all('*',function(req,res,next){
    var uri = req.originalUrl;
    if(uri.startsWith(envConfig.APP.context+"/api/sysuser/isLogin")){
        next();
    }else if(uri.startsWith(envConfig.APP.context+"/api/sysuser/login")){
        next();
    }else if(uri.startsWith(envConfig.APP.context+"/api/sysuser/logout")){
        next();
    }else if(uri.startsWith(envConfig.APP.context+"/outer")){
        next();
    }else if(uri == "/"){
        res.render("index");
    }else{
        if(req.session.sysuser){
            next();
        }else{
            res.redirect("/#!/login");
            res.end();
        }
    }
});

// Globbing express routing files
config.getGlobbedFiles(path.join(__dirname, '/../routes/**/*.js')).forEach(function(routePath) {
    require(path.resolve(routePath))(router);
});
app.use(envConfig.APP.context, router);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development    
    var json = {};
    json.message = err.message;
    json.status = (err.status) ? err.status : 500;
    // render the error page
    res.status(err.status || 500);
    res.json(json);
});

process.on('uncaughtException', function(){})

exports = module.exports = app;
